<?php

namespace App\Models;

use App\EmptyObject;
use App\MongoBaseModel as Model;
use Jenssegers\Mongodb\Eloquent\SoftDeletes;
use MongoDB\BSON\Regex;
use Helper;
use Carbon\Carbon;
use MongoDB\BSON\UTCDateTime;

/**
 * Class Company
 * @package App\Models
 * @property string $id
 * @property string $key
 * @property string $name
 * @property string $email
 * @property string $contact
 * @property string $contactTel
 * @property string $alias
 * @property string $startDate
 * @property string $endDate
 * @property array  $options
 * @property int    $wxClientCount
 * @property object $initUser
 * @property string $created_at
 * @property string $updated_at
 */
class Company extends Model
{
    use SoftDeletes;
    protected $dates = ['deleted_at', 'startDate', 'endDate'];
    protected $casts = [
        'wxClientCount' => 'integer',
        'initUser' => 'object',
    ];
    protected $appends = ['projectCount'];
    protected $hidden = ['initUser'];
    public $timestamps = false;
    const ST_DISABLED = 0;
    const ST_NORMAL = 1;
    const ST_EXPIRED = 2;
    const ST_NOT_STARTED = 3;

    const STATUS = [
        '禁用' => self::ST_DISABLED,
        '正常使用' => self::ST_NORMAL,
        '已到期' => self::ST_EXPIRED,
        '未开始' => self::ST_NOT_STARTED,
    ];

    // 定义输入字段, fieldKey => defaultValue
    // 在这里定义输入字段, 以后有字段变动, 只需更改这里即可, 无需修改控制器逻辑
    const InputFiled = [
        'name' => '',       // 渠道名称(公司名)
        'alias'=>'',        //别名，生成二级域名时使用
        'contact' => '',    // 渠道联系人
        'contactTel' => '', // 渠道联系人联系方式
        'startDate' => null,  // 使用开始时间
        'endDate' => null,    // 使用到期时间star
        'email' => '',      // 联系人E-Mail
        'wxClientCount' => 0, // 分配的微信号数量
        'options' => [
            'ecoModule' => '',
            'canUsePlugin' => false,
            'plugins' => [],
            'customerFields' => [],
            'canShareCustomer' => false,
        ],    // 参数
    ];

    protected $fillable = ['name', 'contact', 'contactTel', 'startDate', 'endDate', 'email', 'wxClientCount', 'options','alias'];

    /**
     * 通过渠道信息获取初始化的渠道账号信息
     * @return array
     */
    public function getInitUserInfo() {
        $name = $this->contact;
        $mobile = $this->contactTel;
        $email = $this->email;
        $company_id = $this->id;
        return compact('name', 'mobile', 'email', 'company_id');
    }
    /**
     * 获取别名
     * @return array
     */
    public function getAlias(){
        $alias = $this->alias;
        return compact('alias');
    }

   public function wxClients() {
       return $this->hasMany(WxClient::class);
   }

   public function getProjectCountAttribute() {
       return $this->wxClients()->used()->count();
   }

   public function scopeSearchByName($query, $name) {
       return $query->where(['name' => new Regex("$name", 'i')]);
   }

    /**
     * @param \Jenssegers\Mongodb\Query\Builder $query
     * @param $status
     * @return mixed
     */
   public function scopeSearchByStatus($query, $status) {
       $today = new UTCDateTime( (new Carbon())->timestamp * 1000);
       if (array_key_exists($status, self::STATUS)) {
           switch (self::STATUS[$status]) {
               case self::ST_DISABLED:
                   return $query->onlyTrashed();
               case self::ST_NOT_STARTED:
                   return $query->where('startDate', '>', $today);
               case self::ST_EXPIRED:
                   return $query->where('endDate', '<', $today);
               case self::ST_NORMAL:
                   return $query
                       ->where([
                           ['startDate', '<=', $today],
                           ['endDate', '>=', $today],
                       ])
                       ->orWhere(function($subQuery) use ($today) {
                           $subQuery->where([
                               ['startDate', '<=', $today],
                               ['endDate', '=', $today]
                           ]);
                       })
                       ->orWhere(function($subQuery) use ($today) {
                           $subQuery->where([
                               ['startDate', '=', null],
                               ['endDate', '>=', $today]
                           ]);
                       })
                       ->orWhere(function($subQuery) {
                           $subQuery->where([
                               'startDate' => null,
                               'endDate' => null,
                           ]);
                       });
           }
       } else {
           return $query->withTrashed();
       }
   }

   public function setStartDateAttribute($value) {
       $this->attributes['startDate'] = (!empty($value)) ? $this->_getDateValue($value) : self::InputFiled['startDate'];
   }

    public function setEndDateAttribute($value) {
        $this->attributes['endDate'] = (!empty($value)) ? $this->_getDateValue($value) : self::InputFiled['endDate'];
    }

    public function getOptionsAttribute() {
        if (empty($this->attributes['options'])) {
            return new EmptyObject();
        }
        return $this->attributes['options'];
    }

    public function setOptionsAttribute($value) {
        $this->attributes['options'] = empty($value) ? new EmptyObject() : $value;
    }

    /**
     * @param $value
     * @return UTCDateTime
     */
    protected function _getDateValue($value) {
        try {
            $r = new Carbon($value);
            return new UTCDateTime($r->timestamp * 1000);
        } catch (\Exception $exception) {
            // nothing to do
        }
        return null;
    }
}
